package com.py.credit.utils;

import com.alibaba.fastjson.JSONArray;
import com.healthmarketscience.sqlbuilder.BinaryCondition;
import com.healthmarketscience.sqlbuilder.CustomSql;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SQLBuilder {
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static List<String> createConditionSql(String conditionStr) {

        List<String> conditionSql = new ArrayList<String>();

        if (StringUtils.isNotBlank(conditionStr))

        {

            List<Map> condition = JSONArray.parseArray(conditionStr, Map.class);

            for (Map<String, Object> column : condition) {

                String type = column.get("type").toString();

                if ((boolean) column.get("fuzzy") && "varchar".equals(type)) {

                    conditionSql.add(BinaryCondition
                            .like(new CustomSql(column.get("colNameEN")), "%" + (String) column.get("value") + "%")
                            .toString());

                } else if ("timestamp".equals(type) || "number".equals(type)) {

                    List<String> values = (List<String>) column.get("value");

                    if (StringUtils.isNotBlank(values.get(0))) {

                        conditionSql.add(BinaryCondition
                                .greaterThan(new CustomSql(column.get("colNameEN")), values.get(0), true).toString());
                    }

                    if (StringUtils.isNotBlank(values.get(1))) {

                        conditionSql.add(BinaryCondition
                                .lessThan(new CustomSql(column.get("colNameEN")), values.get(1), true).toString());

                    }

                } else {

                    conditionSql.add(BinaryCondition
                            .equalTo(new CustomSql(column.get("colNameEN")), column.get("value")).toString());

                }

            }
        }
        return conditionSql;
    }

}
